package ldh.im.fxgui.controller;

import javafx.beans.InvalidationListener;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Popup;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import ldh.im.fxbase.util.BeanFactory;
import ldh.im.fxbase.util.PopupPos;
import ldh.im.fxbase.dao.GroupDao;
import ldh.im.fxbase.help.MovableHelper;
import ldh.im.fxbase.pojo.ImGroup;
import ldh.im.fxbase.pojo.User;
import ldh.im.fxbase.util.RegionUtil;
import ldh.im.fxbase.util.SoftMapUtil;

import java.net.URL;
import java.util.ResourceBundle;

public class MainController implements Initializable {

    @FXML private Pane root;
    @FXML private ImageView headIcon;
    @FXML private VBox contentBox;
    @FXML private Pane contentPane;
    @FXML private Pane leftPane;
    @FXML private Node defaultIcon;
    @FXML private Label settingLabel;

    private Popup popup = new Popup();
    private Pane settingPopupPane = null;
    private Stage settingStage = null;
    private GroupDao groupDao = BeanFactory.getInstance().getBean(GroupDao.class);

    private StringProperty currentProperty = new SimpleStringProperty("");

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        MovableHelper.movable(root);
        Image image = new Image(this.getClass().getResource("/imgs/head.jpg").toExternalForm());
        headIcon.setImage(image);

        showMessagePane(null);

        popup.setAutoHide(true);

        currentProperty.addListener((InvalidationListener)l->{
            leftPane.getChildren().forEach(node->{
                if (node instanceof StackPane) {
                    cleanActiveAndAddDefault(defaultIcon, "MessagePane");
                    return;
                }
                Object obj = node.getUserData();
                if (obj == null) {
                    return;
                }
                cleanActiveAndAddDefault(node, obj.toString());
            });
        });
    }

    @FXML public void showUserPane(MouseEvent mouseEvent) {
        String ownerData = ((Node)mouseEvent.getSource()).getUserData().toString();
        if (currentProperty.get().equals(ownerData)) return;
        currentProperty.set(ownerData);
        Node pane = getCachePane("Main-" + ownerData);
        if (pane == null) {
//            RegionUtil.FxmlBean<Pane, UserController> fxmlBean = RegionUtil.loadFxmlBean(this.getClass().getResource("/fxml/UserPage.fxml"));
            RegionUtil.FxmlBean<Pane, UserTreeController> fxmlBean = RegionUtil.loadFxmlBean(this.getClass().getResource("/fxml/UserTreePage.fxml"));
            SoftMapUtil.cacheWeak("Main-" + ownerData, fxmlBean);
            pane = fxmlBean.getNode();
        }
        showPane(pane);
    }

    @FXML public void showMessagePane(javafx.scene.input.MouseEvent mouseEvent) {
        String ownerData = "MessagePane";
        if (mouseEvent != null) {
            ownerData = ((Node)mouseEvent.getSource()).getUserData().toString();
            if (currentProperty.get().equals(ownerData)) return;
        }
        currentProperty.set(ownerData);
        RegionUtil.FxmlBean<Pane, MessageController> fxmlBean = getCacheFxmlBean("Main-" + ownerData);
        if (fxmlBean == null) {
            fxmlBean = RegionUtil.loadFxmlBean(this.getClass().getResource("/fxml/MessagePage.fxml"));
            SoftMapUtil.cache("Main-" + ownerData, fxmlBean);
            fxmlBean.getController().loadMItemDatas();
        } else {
            fxmlBean.getController().reload();
        }
        showPane(fxmlBean.getNode());
    }

    public void switchUserMessage(User user) {
        try {
            showMessagePane(null);
            RegionUtil.FxmlBean<Pane, MessageController> fxmlBean = getCacheFxmlBean("Main-MessagePane");
            ImGroup mItem = groupDao.getImGroupByUserId(user.getId());
            if (mItem == null) {
                mItem = new ImGroup();
                mItem.setName(user.getUserName());
                mItem.setUserId(user.getId());
                mItem.setNewMessage("");
                mItem.setHotMessageTotal(0);
                groupDao.saveImGroup(mItem);

            }

            fxmlBean.getController().switchMItem(mItem);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showPane(Node pane) {
        contentPane.getChildren().clear();
        contentPane.getChildren().add(pane);
    }

    private Node getCachePane(String key) {
        RegionUtil.FxmlBean<Pane, ?> fxmlBean = SoftMapUtil.getCache(key);
        if (fxmlBean == null) return null;
        return fxmlBean.getNode();
    }

    public <N, C> RegionUtil.FxmlBean<N, C> getCacheFxmlBean(String key) {
        RegionUtil.FxmlBean fxmlBean = SoftMapUtil.getCache(key);
        if (fxmlBean == null) return null;
        return fxmlBean;
    }

    private void cleanActiveAndAddDefault(Node node, String userData){
        if (node.getStyleClass().contains("active")) {
            node.getStyleClass().remove("active");
            node.getStyleClass().add("default-icon");
        }
        if (currentProperty.get().equals(userData)) {
            node.getStyleClass().add("active");
            node.getStyleClass().remove("default-icon");
        }
    }

    @FXML
    public void showSettingPop(MouseEvent mouseEvent) {
        if (settingPopupPane == null) {
            settingPopupPane = createSettingPane();
            popup.getContent().clear();
            popup.getContent().add(settingPopupPane);
        }
        double x = RegionUtil.calcAnchorX(leftPane, PopupPos.up_east, settingPopupPane)+1;
        double y = RegionUtil.calcAnchorY(settingLabel, PopupPos.up_east, settingPopupPane);
        popup.show(settingLabel.getScene().getWindow(), x, y);
    }

    private VBox createSettingPane() {
        VBox vBox = new VBox();
        vBox.setPrefSize(150, 100);
        vBox.getStyleClass().add("setting-popup-pane");
        Button yjfkBtn = new Button("意见反馈");
        Button bfhfBtn = new Button("备份和恢复");
        Button settingBtn = new Button("设置");
        settingBtn.setOnAction((e)->{
            if (settingStage == null) {
                settingStage = new Stage();
                settingStage.initStyle(StageStyle.TRANSPARENT);
                RegionUtil.FxmlBean<Pane, SettingController> settingFxmlBean = RegionUtil.loadFxmlBean(this.getClass().getResource("/fxml/SettingPane.fxml"));
                settingFxmlBean.getController().setStage(settingStage);
                Scene scene = new Scene(settingFxmlBean.getNode());
//                scene.setFill(Color.TRANSPARENT);
                scene.getStylesheets().add(this.getClass().getResource("/css/var.css").toExternalForm());
                scene.getStylesheets().add(this.getClass().getResource("/css/setting.css").toExternalForm());
                scene.getStylesheets().add(this.getClass().getResource("/css/stage.css").toExternalForm());
                scene.getStylesheets().add(this.getClass().getResource("/css/bootstrapfx.css").toExternalForm());
                settingStage.setScene(scene);
                MovableHelper.movable(settingFxmlBean.getController().getMovablePane());
            }
            settingStage.show();
            settingStage.setIconified(false);
        });
        vBox.getChildren().addAll(yjfkBtn, bfhfBtn,settingBtn);
        return vBox;
    }
}
